package com.gk.courses.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gk.courses.dao.StudentDao;
import com.gk.courses.model.Course;
import com.gk.courses.model.Student;

@Repository
public class StudentJpaDao implements StudentDao {

	@PersistenceContext
	private EntityManager em;

	@Override
	public Student findById(int studentId) {
		Query query = em.createQuery("from Student s where s.id = :id");
		query.setParameter("id", studentId);
		return (Student)query.getSingleResult();
	}

	@Override
	public void create(Student student) {
		em.persist(student);
	}
	
	@Override
	public void updateCompletedCourse(Course course, Student student) {
		List<Course> courses = student.getCompletedCourses();
		if (!courses.contains(course)) {
			courses.add(course);
		}
		student.setCompletedCourses(courses);
		em.merge(student);
	}

	@Override
	public List<Course> getCompletedCourses(Student student) {
		return new ArrayList<Course>(student.getCompletedCourses());
	}

	@Override
	public List<Course> getEnrolledCourses(Student student) {
		return new ArrayList<Course>(student.getCourses());
	}
	
}
